<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>首页列表</title>
  <script src="./jquery-3.0.0.min.js"></script>
  <script src="./confing.js"></script>

</head>

<body>
  <div>
    <button onclick="goAdd()">去添加</button> <button onclick="goLogin()">去登录</button>
    <ul>
      <!-- <li>
        事项: <button class="dele" onclick="dele(1)">删除</button> </br>
        发生时间:</br>
        支出类型: </br>
        金额: </br>
        备注: </br>
      </li> -->
    </ul>
  </div>
  <script>
    function goAdd() {
      window.location.href = "./add.html";
    }
    function goLogin() {
      window.location.href = "./login.html";
    }

    $(function () {
      console.log('页面初始化')
      function getList() {
        $('ul').html('');
        $.ajax({
          url: DBHOST+"/account/create",
          type: "GET",
          headers: {
            'Token': localStorage.getItem('token')
          },
          success: function (result) {
            console.log(result);
            let { data, code, msg } = result;
            if (code == 200) {
              data.forEach(item => {
                $('ul').append(
                  `<li>
                事项: ${item.name} <button class="dele" data-id="${item._id}">删除</button></br>
                发生时间:${item.time}</br>
                支出类型: ${item.type == 1 ? '支出' : '收入'}</br>
                金额: ${item.money}</br>
                备注:${item.bark} </br>
              </li>`
                )
              });
            }

          },
          error: function (err) {
            let { code, msg } = err.responseJSON;
            if (code == 999) {
              alert(msg);
              goLogin();
            }
          }
        });
      }
      getList();

      $('ul').delegate('.dele', 'click', function () {
        let id = $(this).attr('data-id');
        let bool = confirm("确定删除?");
        if (bool) {
          $.ajax({
            url: DBHOST+"/account/delete",
            data: { id },
            type: "POST",
            headers: {
              'Token': localStorage.getItem('token')
            },
            success: function (result) {
              console.log(result);
              const { code } = result;
              if (code == 200) {
                getList();
              }
            },
            error: function (err) {
              let { code, msg } = err.responseJSON;
              if (code == 999) {
                alert(msg);
                goLogin();
              }
            }
          });
        }
      })

    })

  </script>
</body>

</html>